//
//  OPLoginTextField.m
//  OpenPractice
//
//  Created by red on 2023/10/11.
//  Copyright © 2023 tanyuehong. All rights reserved.
//

#import "OPLoginTextField.h"


static NSInteger kLoginCodeLength = 4;
static NSInteger kLoginPhoneLength = 11;
static NSInteger kLoginPasswordMinLength = 6;
static NSInteger kLoginPasswordMaxLength = 14;
static const NSInteger kLoginSendCodeInterval = 60;

@interface OPLoginTextField () <UITextFieldDelegate>

@property (nonatomic, strong) UIView *bottomLine;
@property (nonatomic, strong, readwrite) UIButton *clearButton;
@property (nonatomic, strong, readwrite) UIView *clearButtonMask;

@property (nonatomic,   weak) id<YKLoginTextFieldDelegate> innerDelegate;

@end

@implementation OPLoginTextField

- (instancetype)initWithCoder:(NSCoder *)coder {
    return [self initWithText:@"" placeholder:@""];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [self initWithText:@"" placeholder:@""]) {
        self.frame = frame;
    }
    return self;
}

- (instancetype)initWithText:(NSString *)text placeholder:(NSString *)placeholder {
    if (self = [super initWithFrame:CGRectZero]) {
        self.showClearButton = YES;
        self.showBottomLine = YES;
        _hitInsets = UIEdgeInsetsMake(0, -16, 0, -16);
        [super setDelegate:self];
        self.text = text;
        self.font = [UIFont boldSystemFontOfSize:20];
        self.textColor = kTYH333333TextColor;
        UInt32 hexColorInt32 = 0xFE861E;
        UIColor *themeColor = [UIColor colorWithHex:hexColorInt32];
        self.tintColor = themeColor;
        self.placeholder = placeholder;
        self.enablesReturnKeyAutomatically = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textDidChange)
                                                     name:UITextFieldTextDidChangeNotification
                                                   object:self];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSInteger)cursorPosition {
    return [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start];
}

- (BOOL)isCursorAtEnd {
    return self.cursorPosition == self.text.length;
}

- (void)clearAction {
    self.text = nil;
    [self becomeFirstResponder];
}

- (void)textDidChange {
    if ([self.innerDelegate respondsToSelector:@selector(textField:didChangeText:)]) {
        [self.innerDelegate textField:self didChangeText:self.text];
    }
    if (self.showClearButton) {
        self.clearButtonMask.hidden = self.text.length != 0;
        if (!self.isFirstResponder) {
            self.clearButtonMask.hidden = NO;
        }
    }
}

- (void)setPlaceholder:(NSString *)placeholder {
    if (!placeholder) { return; }
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16], NSForegroundColorAttributeName: [UIColor colorWithHex:0xcccccc]}];
}

- (void)setDelegate:(id<YKLoginTextFieldDelegate>)delegate {
    self.innerDelegate = delegate;
}

- (void)setShowBottomLine:(BOOL)showBottomLine {
    _showBottomLine = showBottomLine;
    self.bottomLine.hidden = !showBottomLine;
    if (showBottomLine && !self.bottomLine) {
        self.bottomLine = [[UIView alloc] init];
        self.bottomLine.backgroundColor = [UIColor colorWithHex:0xedeff0];;
        [self addSubview:self.bottomLine];
        [self.bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.equalTo(@(1 / [UIScreen mainScreen].scale));
        }];
    }
}

- (void)setShowClearButton:(BOOL)showClearButton {
    _showClearButton = showClearButton;
    self.clearButton.hidden = !showClearButton && self.text.length;
    if (showClearButton && !self.clearButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"live_login_text_clear"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
        button.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 0);
        [button sizeToFit];
        self.clearButton = button;
        
        UIView *buttonMask = [UIView new];
        buttonMask.hidden = NO;
        buttonMask.backgroundColor = [UIColor whiteColor];
        buttonMask.frame = button.bounds;
        [button addSubview:buttonMask];
        self.clearButtonMask = buttonMask;
        
        UIView *rightView = [[UIView alloc] initWithFrame:button.bounds];
        rightView.translatesAutoresizingMaskIntoConstraints = NO;
        [rightView addSubview:button];
        
        self.rightView = rightView;
        self.rightViewMode = UITextFieldViewModeAlways;
    }
}

- (BOOL)isTextValid {
    return YES;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitInsets);
    return CGRectContainsPoint(hitFrame, point);
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (point.x > CGRectGetMaxX(self.rightView.frame) && point.y >= 0 && point.y <= CGRectGetHeight(self.frame)) {
        // 扩大最右边按钮的点击区域
        return self.rightView.subviews.lastObject;
    }
    return [super hitTest:point withEvent:event];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        return [self.innerDelegate textFieldShouldBeginEditing:textField];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        [self.innerDelegate textFieldDidBeginEditing:textField];
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        return [self.innerDelegate textFieldShouldEndEditing:textField];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        [self.innerDelegate textFieldDidEndEditing:textField];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        return [self.innerDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        return [self.innerDelegate textFieldShouldClear:textField];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([self.innerDelegate respondsToSelector:_cmd]) {
        return [self.innerDelegate textFieldShouldReturn:textField];
    }
    return YES;
}

- (BOOL)canBecomeFirstResponder {
    //为了在展示闪屏页面的时候不弹出键盘
    __block BOOL hasSplash = NO;
    [[UIApplication sharedApplication].windows enumerateObjectsUsingBlock:^(__kindof UIWindow * obj, NSUInteger idx, BOOL *stop) {
        if ([obj.rootViewController isKindOfClass:NSClassFromString(@"LiveSplashADViewController")]) {
            hasSplash = YES;
            *stop = YES;
        }
    }];
    if (!hasSplash) {
//        [LoginManager sharedInstance].loginIputTextField = self.description;
        return YES;
    }
    return NO;

}

@end

#import "CHRPhoneNumberMask.h"
#import "CHRTextFieldFormatter.h"


@interface LoginPhoneTextField ()

@property (nonatomic, strong) CHRTextFieldFormatter *phoneNumberFormatter;

@end

@implementation LoginPhoneTextField

- (instancetype)initWithPhone:(NSString *)phone {
    if (self = [super initWithText:phone placeholder:@"请输入手机号"]) {
        _phoneNumberFormatter = [[CHRTextFieldFormatter alloc] initWithTextField:self mask:[CHRPhoneNumberMask new]];
        self.text = phone;
        self.keyboardType = UIKeyboardTypePhonePad;
    }
    return self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self.phoneNumberFormatter textField:self shouldChangeCharactersInRange:range replacementString:string];
}

- (void)textDidChange {
    if (self.text.length > kLoginPhoneLength + 2) {
        self.text = [self.text substringToIndex:kLoginPhoneLength + 2];
        [self.undoManager removeAllActions];
    }
    [super textDidChange];
}

- (void)setText:(NSString *)text {
    NSString *newMask = [self.phoneNumberFormatter maskedStringFromString:text];
    NSString *oldMask = [self.phoneNumberFormatter maskedStringFromString:self.text];
    [super setText:newMask];
    
    if (![newMask isEqualToString:oldMask]) {
        [self textDidChange];
    }
}

- (BOOL)isTextValid {
    return self.text.length == kLoginPhoneLength + 2;
}

@end

@interface LoginPasswordTextField ()

@property (nonatomic, strong) UIButton *secureButton;

@end

@implementation LoginPasswordTextField

- (instancetype)initWithText:(NSString *)text placeholder:(NSString *)placeholder {
    if (self = [super initWithText:text placeholder:placeholder]) {
        self.secureTextEntry = YES;
        self.returnKeyType = UIReturnKeyDone;
        self.showSecurityButton = YES;
    }
    return self;
}

- (void)showPassword:(UIButton *)button {
    button.selected = !button.selected;
    self.secureTextEntry = button.selected;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [super textFieldDidBeginEditing:textField];
    // 解决密码重新输入被清空的问题
    if (textField.secureTextEntry) {
        textField.text = textField.text;
    }
}

- (void)setText:(NSString *)text {
    BOOL textChanged = ![text isEqualToString:self.text];
    [super setText:text];
    
    if (textChanged) {
        [self textDidChange];
    }
}

- (void)textDidChange {
    if (self.text.length > kLoginPasswordMaxLength) {
        self.text = [self.text substringToIndex:kLoginPasswordMaxLength];
        [self.undoManager removeAllActions];
    }
    [super textDidChange];
}

- (void)setShowSecurityButton:(BOOL)showSecurityButton {
    _showSecurityButton = showSecurityButton;
    self.secureButton.hidden = !showSecurityButton;
    UIView *rightView = self.rightView ?: [[UIView alloc] init];
    rightView.translatesAutoresizingMaskIntoConstraints = NO;
    if (showSecurityButton) {
        if (!self.secureButton) {
            UIButton *showPswButton = [UIButton buttonWithType:UIButtonTypeCustom];
            showPswButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 0);
            showPswButton.selected = YES;
            [showPswButton setImage:[UIImage imageNamed:@"live_login_displayPassword"] forState:UIControlStateNormal];
            [showPswButton setImage:[UIImage imageNamed:@"live_login_hidePassword"] forState:UIControlStateSelected];
            [showPswButton addTarget:self action:@selector(showPassword:) forControlEvents:UIControlEventTouchUpInside];
            [showPswButton sizeToFit];
            [rightView addSubview:showPswButton];
            [self.clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(rightView);
            }];
            [self.clearButtonMask mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.bottom.right.equalTo(self.clearButton);
            }];
            [showPswButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.clearButton.mas_right).offset(2);
                make.right.centerY.equalTo(rightView);
            }];
        }
        [rightView.widthAnchor constraintEqualToConstant:80].active = YES;
        [rightView.heightAnchor constraintEqualToConstant:40].active = YES;
    } else {
        [rightView.widthAnchor constraintEqualToConstant:self.clearButton.frame.size.width].active = YES;
        [rightView.heightAnchor constraintEqualToConstant:40].active = YES;
    }
    self.rightView = rightView;
}

- (void)setSecureTextEntry:(BOOL)secureTextEntry {
    [super setSecureTextEntry:secureTextEntry];
    self.secureButton.selected = secureTextEntry;
}

- (BOOL)isTextValid {
    return self.text.length >= kLoginPasswordMinLength && self.text.length <= kLoginPasswordMaxLength;
}

@end

@interface LoginCodeTextField ()

@property (nonatomic,   weak) id sendCodeTarget;
@property (nonatomic, assign) SEL sendCodeSelector;

@end

@implementation LoginCodeTextField

- (instancetype)initWithSendCodeTarget:(id)target selector:(SEL)selector {
    if (self = [super initWithText:@"" placeholder:@"请输入验证码"]) {
        _sendCodeTarget = target;
        _sendCodeSelector = selector;
        self.keyboardType = UIKeyboardTypeNumberPad;
        self.clearButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [self loadSendCodeButton];
    }
    return self;
}

- (void)loadSendCodeButton {
    self.sendCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendCodeButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.sendCodeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.sendCodeButton.enabled = NO;
    
    UInt32 hexColorInt32 = 0xFE861E;
    UIColor *themeColor = [UIColor colorWithHex:hexColorInt32];
    [self.sendCodeButton setTitleColor:themeColor forState:UIControlStateNormal];
    
    
    [self.sendCodeButton setTitleColor:[UIColor colorWithHex:0x9da0a3] forState:UIControlStateDisabled];
    [self.sendCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.sendCodeButton addTarget:self.sendCodeTarget action:self.sendCodeSelector forControlEvents:UIControlEventTouchUpInside];
    UIView *rightView = self.rightView;
    rightView.translatesAutoresizingMaskIntoConstraints = NO;
    [rightView.widthAnchor constraintEqualToConstant:160].active = YES;
    [rightView addSubview:self.sendCodeButton];
    self.rightView = rightView;
    
    [self.clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(rightView);
    }];
    [self.clearButtonMask mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self.clearButton);
    }];
    [self.sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.equalTo(rightView);
        make.left.equalTo(self.clearButton.mas_right).offset(2);
    }];
}

- (void)setTimeLeft:(NSInteger)timeLeft canSendCode:(BOOL)canSendCode isResendCode:(BOOL)isResendCode{
    if (timeLeft > 0 && timeLeft <= kLoginSendCodeInterval) {
        self.sendCodeButton.enabled = NO;
        [self.sendCodeButton setTitle:[NSString stringWithFormat:@"已发送(%lds)", timeLeft] forState:UIControlStateDisabled];
    } else {
        self.sendCodeButton.enabled = canSendCode;
        [self.sendCodeButton setTitle:@"获取验证码" forState:UIControlStateDisabled];
        [self.sendCodeButton setTitle:isResendCode ? @"重新获取" : @"获取验证码" forState:UIControlStateNormal];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (!string.length) {
        return YES;
    }
    if (self.text.length >= kLoginCodeLength) {
        return NO;
    }
    NSString *pureIntegerRegex = @"^[0-9]+$";
    NSPredicate *pureIntegerTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pureIntegerRegex];
    return [pureIntegerTest evaluateWithObject:string];
}

- (void)setText:(NSString *)text {
    BOOL textChanged = ![text isEqualToString:self.text];
    [super setText:text];
    
    if (textChanged) {
        [self textDidChange];
    }
}

- (void)textDidChange {
    if (self.text.length > kLoginCodeLength) {
        self.text = [self.text substringToIndex:kLoginCodeLength];
        [self.undoManager removeAllActions];
    }
    [super textDidChange];
}

- (BOOL)isTextValid {
    return self.text.length == kLoginCodeLength;
}

@end
